package com.dliyun.oap.framework.impl;

import com.dliyun.oap.framework.security.FileUploadController;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <pre>
 *    1.如果maxSize为非正数，则表示不限制大小；
 *    2.如果allowAllTypes为true表示不限制文件类型；
 * </pre>
 *
 * @author stjdydayou
 * @version 1.0
 */
public class DefaultFileUploadController implements FileUploadController {

    private List<String> fileTypes;

    private int maxSize;

    @Override
    public boolean isAllowFileType(String fileType) {
        if (fileTypes == null) {
            return true;
        } else {
            if (fileType == null) {
                return false;
            } else {
                fileType = fileType.toLowerCase();
                return fileTypes.contains(fileType);
            }
        }
    }


    @Override
    public boolean isExceedMaxSize(int fileSize) {
        if (maxSize > 0) {
            return fileSize > maxSize * 1024;
        } else {
            return false;
        }
    }


    @Override
    public String getAllowFileTypes() {
        if (CollectionUtils.isEmpty(fileTypes)) {
            return "";
        } else {
            StringBuilder sb = new StringBuilder();
            String seprator = "";
            for (String fileType : fileTypes) {
                sb.append(seprator);
                sb.append(fileType);
                seprator = ",";
            }
            return sb.toString();
        }
    }


    @Override
    public int getMaxSize() {
        return this.maxSize;
    }

    @Override
    public void setFileTypes(List<String> fileTypes) {
        this.fileTypes = fileTypes;
    }

    @Override
    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
    }
}

